package project3.association;

import java.text.DecimalFormat;

import project3.datasets.Attribute;
import project3.datasets.DataSet;

/**
 * Helper class used to display rules.
 * 
 * @author Antonio
 * @author Vika
 */
public class RuleToString {

	private final DataSet dataSet;

	private DecimalFormat format = new DecimalFormat(".##");
	
	public RuleToString(DataSet dataSet) {
		super();
		this.dataSet = dataSet;
	}
	
	public String toString(AssociationRule rule) {
		StringBuilder buff = new StringBuilder();
		itemSetToString(rule.getPremise(), buff, false);
		
		buff.append(" => ");
		
		itemSetToString(rule.getConsequence(), buff, false);
		
		buff.append(" (Confidence=").append(displayConfidence(rule)).append("%,");
		buff.append(" Support=").append(format.format(rule.getSupport())).append("%)");
		
		return buff.toString();
	}

	private String displayConfidence(AssociationRule rule) {
		return format.format(rule.getConfidence() * 100);
	}

	private String displaySupport(ItemSet itemSet) {
		
		return format.format(itemSet.getSupport() * 100 / this.dataSet.size());
	}
	
	
	/**
	 * @param itemSet
	 * @param buff
	 * @param includeSupport
	 */
	public void itemSetToString(ItemSet itemSet, StringBuilder buff, boolean includeSupport) {
		double[] premiseRawValues = itemSet.getRawValues();
		boolean firstPremise = true;
		buff.append("[ ");
		for (int i = 0; i < premiseRawValues.length; i++) {
			if (premiseRawValues[i] == -1) {
				continue;
			}
			
			Attribute attribute = this.dataSet.getAttributes()[i];

			if (false == firstPremise) {
				buff.append(" AND ");
				firstPremise = false;
			}
			
			buff.append(attribute.getName()).append("=");
			buff.append(attribute.decode(premiseRawValues[i]));
			buff.append("  ");
		}
		buff.append("]");
	
		if(includeSupport)
			buff.append(" (Support=").append(displaySupport(itemSet)).append("%)");
	}

}
